package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 1、通过HTTPClient构造登录凭证校验请求
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        log.info("微信登录返回结果：{}", res);
        // 2、获取登录凭证校验结果，获取OpenID
        // 2.1 解析返回结果，获取OpenID
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = jsonObject.get("openid").toString();
        if (openid == null || openid.isEmpty()) {
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }
        // 3、是否为新用户，根据OpenID查询User表
        User user = userMapper.selectByOpenId(openid);
        if (user == null) {
            // 3.1 如果用户不存在，则创建新用户
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            user.setName(openid.substring(0, 5));
            userMapper.insert(user);
        }
        // 4、如果登录成功，则返回用户信息
        return user;
    }
}
